package com.domus.dreamMenu.cliente.util;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.domus.dreamMenu.tipos.ItemNoticia;

public class ServicoNoticias {

	public static ArrayList<ItemNoticia> getNoticias(String url){
		try {
			Document documento = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url);
			
			Node auxiliar;
			NodeList rss = documento.getChildNodes().item(0).getChildNodes();
			
			NodeList channel;
			NodeList item;
			ArrayList<ItemNoticia> noticias = new ArrayList<ItemNoticia>();
			
			for(int i = 0; i < rss.getLength(); i++){
				auxiliar = rss.item(i);
				if(auxiliar.getNodeType() == Node.ELEMENT_NODE
						&& ((Element) auxiliar).getTagName().equalsIgnoreCase("channel")){
					
					channel = auxiliar.getChildNodes();
					
					for(int j = 0; j < channel.getLength(); j++){
						auxiliar = channel.item(j);
						if(auxiliar.getNodeType() == Node.ELEMENT_NODE
								&& ((Element) auxiliar).getTagName().equalsIgnoreCase("item")){
							
							item = auxiliar.getChildNodes();
							
							String titulo = null, descricao = null;
							for(int k = 0; k < item.getLength(); k++){
								auxiliar = item.item(k);
								
								if(auxiliar.getNodeType() == Node.ELEMENT_NODE){
									if(((Element) auxiliar).getTagName().equalsIgnoreCase("title")){
										titulo = auxiliar.getTextContent();
										
									}
									else if(((Element) auxiliar).getTagName().equalsIgnoreCase("description"))
										descricao = auxiliar.getTextContent();
								}
							}
							
							noticias.add(new ItemNoticia(titulo, descricao));
						}
					}
				}
			}
			
			return noticias;
			
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//TODO
		return null;
	}
}
